package com.learn.cloud.validator.constraints;

import com.learn.cloud.validator.annotation.ExtensionValidation;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @description: 文件拓展名校验器实现
 * @author: cong zhi
 * @createDate: 2022/2/6 16:55
 * @updateUser: cong zhi
 * @updateDate: 2022/2/6 16:55
 * @updateRemark: 修改内容
 * @version: v1.0
 */
public class FileExtensionValidator implements ConstraintValidator<ExtensionValidation, MultipartFile> {

    private static final String ANY = "*";

    private String[] extensions;

    @Override
    public void initialize(ExtensionValidation constraintAnnotation) {
        this.extensions = constraintAnnotation.extensions();
    }

    @Override
    public boolean isValid(MultipartFile value, ConstraintValidatorContext context) {
        String detectExtension = FilenameUtils.getExtension(value.getName());
        for (String extension : extensions) {
            if (ANY.equals(extension) || extension.equalsIgnoreCase(detectExtension)) {
                return true;
            }
        }
        return false;
    }
}
